<template>
    <div class="grade-management">
      <el-card class="main-card">
        <div class="header-bar">
          <div class="tabs">
            
          </div>
          <div class="filters">
            <el-select v-model="course" placeholder="课程" style="width: 180px; margin-right: 8px;" @change="onCourseChange" clearable :no-data-text="'暂无已完成考试课程'">
              <el-option v-for="item in courseOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-select v-model="examId" placeholder="考试场次" style="width: 180px; margin-right: 8px;" v-if="examOptions.length">
              <el-option v-for="item in examOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
        </div>
        <el-table :data="gradeList" border style="margin-top: 16px;" :row-class-name="rowClass">
          <el-table-column prop="studentCode" label="学号" min-width="90" />
          <el-table-column prop="studentName" label="姓名" min-width="90" />
          <el-table-column prop="dailyGrade" label="平时成绩" min-width="90" />
          <el-table-column prop="midtermGrade" label="期中成绩" min-width="90" />
          <el-table-column prop="finalGrade" label="期末成绩" min-width="90" />
          <el-table-column prop="totalGrade" label="总评成绩" min-width="90" />
          <el-table-column prop="gradeStatus" label="状态" min-width="80">
            <template #default="{ row }">
              <el-tag :type="statusTagType(row.gradeStatus)">{{ statusLabel(row.gradeStatus) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" min-width="120">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" icon="el-icon-edit" @click="openEditDialog(row)">编辑</el-button>
                <el-button size="small" icon="el-icon-delete" type="danger" @click="deleteGrade(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="table-footer">
          <el-pagination
            background
            layout="prev, pager, next, jumper, ->, total"
            :total="total"
            :page-size="pageSize"
            v-model:current-page="page"
            @current-change="fetchGradeList"
          />
        </div>
        <div class="stats-section">
          <el-row gutter="24">
            <el-col :span="6">
              <el-card class="stat-card">
                <div>参考人数</div>
                <div class="stat-value">{{ stats.studentCount }}</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div>及格人数</div>
                <div class="stat-value">{{ stats.passCount }}</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div>平均分</div>
                <div class="stat-value">{{ stats.avgGrade }}</div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card class="stat-card">
                <div>及格率</div>
                <div class="stat-value">{{ stats.passRate }}%</div>
              </el-card>
            </el-col>
          </el-row>
          <el-card class="chart-card" style="margin-top: 16px;">
            <div>成绩分布</div>
            <div ref="chartRef" style="height: 220px; width: 100%;"></div>
          </el-card>
        </div>
      </el-card>
      <el-dialog title="编辑成绩" v-model="editDialogVisible" width="500px">
        <el-form :model="editForm" label-width="100px">
          <el-form-item label="平时成绩">
            <el-input-number v-model="editForm.dailyGrade" :min="0" :max="100" @change="calcTotalGrade" />
          </el-form-item>
          <el-form-item label="期中成绩">
            <el-input-number v-model="editForm.midtermGrade" :min="0" :max="100" @change="calcTotalGrade" />
          </el-form-item>
          <el-form-item label="期末成绩">
            <el-input-number v-model="editForm.finalGrade" :min="0" :max="100" @change="calcTotalGrade" />
          </el-form-item>
          <el-form-item label="总评成绩">
            <el-input v-model="editForm.totalGrade" disabled />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit">保存</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, nextTick, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import * as echarts from 'echarts'
  import axios from 'axios'
  
  const activeTab = ref('input')
 
  const course = ref(null)
  const search = ref('')
  const page = ref(1)
  const pageSize = 10
  const total = ref(0)
  const gradeList = ref([])
  const stats = reactive({
    studentCount: 0,
    passCount: 0,
    avgGrade: 0,
    passRate: 0,
    distribution: []
  })
  
  const courseOptions = ref([])
  const importUrl = '/api/grade/input'
  const chartRef = ref(null)
  const examId = ref('')
  const examOptions = ref([])
  const editDialogVisible = ref(false)
  const editForm = reactive({})
  
  async function fetchCourseOptions() {
    const { data } = await axios.get('/api/exam/arrange/completedCourses')
    courseOptions.value = (data.data || []).map(item => ({
      label: item.courseName,
      value: item.courseId
    }))
 
  }
  
  async function fetchGradeList() {
    if (!course.value) {
      gradeList.value = []
      total.value = 0
      return
    }
    const params = {
      page: page.value,
      pageSize,
      search: search.value
    }
    const { data } = await axios.get(`/api/grade/course/${course.value}`, { params })
    gradeList.value = data.data.list || []
    total.value = data.data.total || 0
    Object.assign(stats, data.data.stats || {})
    stats.distribution = data.data.distribution || []
    renderChart()
  }
  
  function resetFilters() {
    term.value = termOptions[0]
    course.value = null
    search.value = ''
    fetchGradeList()
  }
  
  function downloadTemplate() {
    window.open('/api/grade/template', '_blank')
  }
  

  function openEditDialog(row) {
    Object.assign(editForm, row)
    editDialogVisible.value = true
  }
  function calcTotalGrade() {
    editForm.totalGrade =
      (Number(editForm.dailyGrade) || 0) * 0.3 +
      (Number(editForm.midtermGrade) || 0) * 0.3 +
      (Number(editForm.finalGrade) || 0) * 0.4
  }
  async function saveEdit() {
    calcTotalGrade()
    await axios.post('/api/grade/input', {
      course_id: course.value,
      exam_id: examId.value,
      grade_list: [
        {
          student_code: editForm.studentCode,
          daily_grade: editForm.dailyGrade,
          midterm_grade: editForm.midtermGrade,
          final_grade: editForm.finalGrade,
          total_grade: editForm.totalGrade,
          grade_status: editForm.gradeStatus || 'NORMAL'
        }
      ]
    })
    ElMessage.success('保存成功')
    editDialogVisible.value = false
    if (examId.value) {
      const { data } = await axios.get(`/api/grade/exam-grades`, {
        params: { examId: examId.value, courseId: course.value }
      })
      gradeList.value = data.data || []
      updateStatsAndChart()
    }
  }
  async function deleteGrade(row) {
    await axios.post('/api/grade/input', {
      course_id: course.value,
      exam_id: examId.value,
      grade_list: [
        {
          student_code: row.studentCode,
          daily_grade: row.dailyGrade,
          midterm_grade: row.midtermGrade,
          final_grade: null,
          total_grade: null,
          grade_status: row.gradeStatus || 'NORMAL'
        }
      ]
    })
    ElMessage.success('已清空期末成绩和总评成绩')
    if (examId.value) {
      const { data } = await axios.get(`/api/grade/exam-grades`, {
        params: { examId: examId.value, courseId: course.value }
      })
      gradeList.value = data.data || []
      updateStatsAndChart()
    }
  }
  function updateStatsAndChart() {
    const list = gradeList.value
    stats.studentCount = list.length
    stats.passCount = list.filter(g => Number(g.totalGrade) >= 60).length
    stats.avgGrade = list.length ? (list.reduce((sum, g) => sum + (Number(g.totalGrade) || 0), 0) / list.length).toFixed(2) : 0
    stats.passRate = list.length ? ((stats.passCount / list.length) * 100).toFixed(2) : 0
    // 成绩分布统计
    const distribution = [0, 0, 0, 0, 0]
    list.forEach(g => {
      const score = Number(g.totalGrade) || 0
      if (score < 60) distribution[0]++
      else if (score < 70) distribution[1]++
      else if (score < 80) distribution[2]++
      else if (score < 90) distribution[3]++
      else distribution[4]++
    })
    stats.distribution = distribution
    renderChart()
  }
  function statusTagType(status) {
    switch (status) {
      case 'NORMAL': return 'success'
      case 'ABSENT': return 'danger'
      case 'CHEAT': return 'warning'
      case 'DELAYED': return 'info'
      default: return ''
    }
  }
  function statusLabel(status) {
    switch (status) {
      case 'NORMAL': return '正常'
      case 'ABSENT': return '缺考'
      case 'CHEAT': return '作弊'
      case 'DELAYED': return '缓考'
      default: return status
    }
  }
  function rowClass({ row }) {
    if (row.grade_status === 'ABSENT' || row.grade_status === 'CHEAT') {
      return 'row-abnormal'
    }
    return ''
  }
  function renderChart() {
    nextTick(() => {
      if (!chartRef.value) return
      const chart = echarts.init(chartRef.value)
      chart.setOption({
        xAxis: { type: 'category', data: ['0-59', '60-69', '70-79', '80-89', '90-100'] },
        yAxis: { type: 'value' },
        series: [{ type: 'bar', data: stats.distribution, name: 'count' }]
      })
    })
  }
  async function onCourseChange(val) {
    examId.value = ''
    if (!val) {
      examOptions.value = []
      return
    }
    const { data } = await axios.get(`/api/grade/completed-exams/${val}`)
    examOptions.value = (data.data || []).map(e => ({
      label: `${e.examName}（${e.examDate?.slice(0,10)} ${e.startTime}-${e.endTime}）`,
      value: e.examId
    }))
  }
  watch(examId, async (val) => {
    if (!val) {
      gradeList.value = []
      // 清空统计
      stats.studentCount = 0
      stats.passCount = 0
      stats.avgGrade = 0
      stats.passRate = 0
      stats.distribution = []
      renderChart()
      return
    }
    if (!course.value) {
      gradeList.value = []
      // 清空统计
      stats.studentCount = 0
      stats.passCount = 0
      stats.avgGrade = 0
      stats.passRate = 0
      stats.distribution = []
      renderChart()
      return
    }
    // 重新统计
    const { data } = await axios.get(`/api/grade/exam-grades`, {
      params: { examId: val, courseId: course.value }
    })
    gradeList.value = data.data || []
    // 统计
    const list = gradeList.value
    stats.studentCount = list.length
    stats.passCount = list.filter(g => Number(g.totalGrade) >= 60).length
    stats.avgGrade = list.length ? (list.reduce((sum, g) => sum + (Number(g.totalGrade) || 0), 0) / list.length).toFixed(2) : 0
    stats.passRate = list.length ? ((stats.passCount / list.length) * 100).toFixed(2) : 0
    // 成绩分布统计
    const distribution = [0, 0, 0, 0, 0]
    list.forEach(g => {
      const score = Number(g.totalGrade) || 0
      if (score < 60) distribution[0]++
      else if (score < 70) distribution[1]++
      else if (score < 80) distribution[2]++
      else if (score < 90) distribution[3]++
      else distribution[4]++
    })
    stats.distribution = distribution
    renderChart()
  })
  onMounted(() => {
    fetchCourseOptions()
    fetchGradeList()
    renderChart()
  })
  </script>
  
  <style scoped>
  .grade-management {
    /* padding: 24px; */
    padding: 0;
  }
  .main-card {
    min-height: 700px;
    width: 100%;
    border-radius: 0;
    box-shadow: none;
  }
  .header-bar {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px 24px;
  }
  .tabs {
    flex: 1;
  }
  .filters {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .table-footer {
    margin: 16px 0 0 0;
    text-align: right;
  }
  .stats-section {
    margin-top: 24px;
  }
  .stat-card {
    text-align: center;
    font-size: 16px;
  }
  .stat-value {
    font-size: 28px;
    font-weight: bold;
    margin-top: 8px;
  }
  .chart-card {
    min-height: 260px;
  }
  .row-abnormal {
    background: #fff1f0 !important;
  }
  .el-button {
    display: flex;
    align-items: center;
    justify-content: center;
    /* 保证按钮内文字和图标都居中 */
  }
  .action-buttons {
    display: flex;
    gap: 8px;
  }
  .action-buttons .el-button {
    min-width: 60px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 12px;
    font-size: 14px;
  }
  </style> 